package struts.ext.util.converter;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;


public class DateFormatter implements AttrFormatter {

	private String formatter = "yyyy-MM-dd hh:mm:ss";
	private DateFormat format;
	
	
	/**
	 * 默认的格式化格式是 yyyy-MM-dd hh:mm:ss
	 */
	public DateFormatter(){
		format = new SimpleDateFormat(formatter);
	}
	
	/**
	 * 提供一个格式化的参数来格式化日期
	 * 默认的格式化格式是 yyyy-MM-dd hh:mm:ss
	 * @param formatter
	 */
	public DateFormatter(String formatter) {
		if(formatter != null && formatter.length() > 0 ){
			this.formatter = formatter;
		}
		format = new SimpleDateFormat(formatter);
	}
	
	@Override
	public String format(Object value) throws Exception  {
		if(value instanceof java.util.Date){
			try{
				return format.format((Date)value);
			}catch(Exception e){
				throw new Exception("格式化失败:" + e.getMessage());
			}
		}
		throw new Exception("格式化失败。" + value + "不是Boolean类型数据");
	}

}
